﻿using HomagChina.Basic.CCT.Tools;
using HomagGroup.Base;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
namespace Proxy
{
    public class DealWithBatchFile
    {
        public static string FolderPath;
        public static string HistoryFolderPath;
        public static string MprFolderPath;
        //public static string MachineFolderPath;
        //public static string MachinesIp;
        //public static List<string> MachinesFolderPath;
        public static string SuffixForCsv;
        public static string SuffixForPnx;
        public static string SuffixForMpr;
        public static char SeparatorForCsv;
        public static char SeparatorForPnx;
        //public bool SaveFeedback;

        public DealWithBatchFile()
        {
            FolderPath = ConfigurationManager.AppSettings["FolderPath"];//@"D:\machine1\data\cct-nesting\Batch";//
            HistoryFolderPath = ConfigurationManager.AppSettings["HistoryFolderPath"]; //@"D:\machine1\data\cct-nesting\BatchHistory\";
            MprFolderPath = ConfigurationManager.AppSettings["MprFolderPath"]; //@"D:\machine1\data\cct-nesting\MprHistory\";
            //MachineFolderPath = ConfigurationManager.AppSettings["MprPath"];//@"\\192.3.60.101\D:\ww4\a1\mp4\,\\192.3.60.102\D:\ww4\a1\mp4\,\\192.3.60.103\D:\ww4\a1\mp4\";//
            SuffixForCsv = ConfigurationManager.AppSettings["FileSuffixForCsv"];//".csv";
            SuffixForPnx = ConfigurationManager.AppSettings["FileSuffixForPnx"];// ".pnx";
            SuffixForMpr = ConfigurationManager.AppSettings["FileSuffixForMpr"];// ".pnx";
            SeparatorForCsv = ConfigurationManager.AppSettings["SeparatorForCsv"].ToChar();//';';
            SeparatorForPnx = ConfigurationManager.AppSettings["SeparatorForPnx"].ToChar();//',';
            //var machineFolderPath = MachineFolderPath.Split(',');
            //MachinesFolderPath = new List<string>();
            //for (int i = 0; i < machineFolderPath.Length; i++)
            //{
            //    MachinesFolderPath.Add(machineFolderPath[i]);
            //}
            //SaveFeedback = false;
            //Task.Factory.StartNew(() => LogicalProcessing(FolderPath));
        }

        /// <summary>
        /// 双层级文件夹
        /// </summary>
        /// <param name="Source"></param>
        public DealWithBatchFile(string Source)
        {
            FolderAnalyzer folderAnalyzer = new FolderAnalyzer();
            NestingCsvAnalyzer nestingCsvAnalyzer = new NestingCsvAnalyzer();
            NestingPnxAnalyzer nestingPnxAnalyzer = new NestingPnxAnalyzer();
            try
            {
                string[] files = Directory.GetFiles(Source);

                // 实例化DirectoryInfo对象
                DirectoryInfo dirInfo = new DirectoryInfo(Source);

                // 获取文件夹下所有子文件夹和文件
                DirectoryInfo[] dirs = dirInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
                //存在待处理的批次文件
                if (dirs.Length > 0)
                {
                    for (int i = 0; i <= dirs.Length - 1; i++)
                    {
                        //调用Tools 拆分文件
                        //查找批次文件夹内Csv文件
                        var CsvFileName = folderAnalyzer.ObtainBatchInfoDetailPath(Source, SuffixForCsv, i);
                        if (string.IsNullOrEmpty(CsvFileName))
                        {
                            dirs[0].Delete();
                            continue;
                        }
                        if (nestingCsvAnalyzer.DealWithCsvFile(CsvFileName, SeparatorForCsv))
                        {
                            //查找批次文件夹内Pnx文件 
                            var PnxFileName = folderAnalyzer.ObtainBatchInfoDetailPath(Source, SuffixForPnx, i);
                            if (string.IsNullOrEmpty(PnxFileName))
                            {
                                continue;
                            }
                        StartPnx:
                            if (nestingPnxAnalyzer.DealWithPnxFile(PnxFileName, SeparatorForPnx))
                            {
                                folderAnalyzer.ObtainBatchInfoDetailPathForCopy(Source, MprFolderPath, ".mpr", i);
                            }
                            else
                            {
                                goto StartPnx;
                            }
                        }
                        else
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_System.Information("加载CSV数据时出现了错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 单层级文件夹
        /// </summary>
        /// <param name="Source"></param>
        public void DealWithBatchFiles(string Source)
        {
            FolderAnalyzer folderAnalyzer = new FolderAnalyzer();
            NestingCsvAnalyzer nestingCsvAnalyzer = new NestingCsvAnalyzer();
            NestingPnxAnalyzer nestingPnxAnalyzer = new NestingPnxAnalyzer();
            try
            {
                string[] files = Directory.GetFiles(Source);

                //存在待处理的批次文件
                if (files.Length > 0)
                {
                    var csvName = files.FirstOrDefault(s => s.EndsWith(".csv"));
                    if (nestingCsvAnalyzer.DealWithCsvFile(csvName, SeparatorForCsv))
                    {
                    StartPnx:
                        var pnxName = files.FirstOrDefault(s => s.EndsWith(".pnx"));
                        if (nestingPnxAnalyzer.DealWithPnxFile(pnxName, SeparatorForPnx))
                        {
                            for (int i = 2; i <= files.Length - 1; i++)
                            {
                                var filename = files[i].Split('\\').LastOrDefault();
                                File.Copy(files[i], MprFolderPath + filename);
                            }
                        }
                        else
                        {
                            goto StartPnx;
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                SerilogHandle.Logger_System.Information("加载CSV数据时出现了错误：" + ex.Message);
            }
        }

        //----------------------------------------------------------//
        public void LogicalProcessing(string FolderPath)
        {
            FolderAnalyzer folderAnalyzer = new FolderAnalyzer();
            NestingCsvAnalyzer nestingCsvAnalyzer = new NestingCsvAnalyzer();
            NestingPnxAnalyzer nestingPnxAnalyzer = new NestingPnxAnalyzer();
            do
            {
            Start:
                try
                {
                    Thread.Sleep(5000);
                    // 实例化DirectoryInfo对象
                    DirectoryInfo dirInfo = new DirectoryInfo(FolderPath);

                    // 获取文件夹下所有子文件夹和文件
                    DirectoryInfo[] dirs = dirInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
                    //存在待处理的批次文件
                    if (dirs.Length > 0)
                    {
                        for (int i = 0; i <= dirs.Length - 1; i++)
                        {
                            //调用Tools 拆分文件
                            //查找批次文件夹内Csv文件
                            var CsvFileName = folderAnalyzer.ObtainBatchInfoDetailPath(FolderPath, SuffixForCsv, i);
                            if (string.IsNullOrEmpty(CsvFileName))
                            {
                                dirs[0].Delete();
                                continue;
                            }
                            if (nestingCsvAnalyzer.DealWithCsvFile(CsvFileName, SeparatorForCsv))
                            {
                                //查找批次文件夹内Pnx文件
                                var PnxFileName = folderAnalyzer.ObtainBatchInfoDetailPath(FolderPath, SuffixForPnx, i);
                                if (string.IsNullOrEmpty(PnxFileName))
                                {
                                    continue;
                                }
                            StartPnx:
                                if (nestingPnxAnalyzer.DealWithPnxFile(PnxFileName, SeparatorForPnx))
                                {
                                    folderAnalyzer.ObtainBatchInfoDetailPathForCopy(FolderPath, MprFolderPath, ".mpr", 0);

                                    #region 多个层级的情况
                                    // 实例化DirectoryInfo对象
                                    DirectoryInfo dirInfo1 = new DirectoryInfo(dirs[i].FullName + "\\");

                                    // 获取文件夹下所有子文件夹和文件
                                    DirectoryInfo[] dirs1 = dirInfo1.GetDirectories("*.*", SearchOption.TopDirectoryOnly);

                                    if (dirs1.Length > 0)
                                    {
                                        dirs1[i].MoveTo(HistoryFolderPath + dirs1[i].Name);
                                    }
                                    else
                                    {
                                        //数据处理成功 //将该文件夹移动到历史文件中  文件夹一个层级的情况
                                        dirs[i].MoveTo(HistoryFolderPath + dirs[i].Name);
                                    }
                                    #endregion

                                }
                                else
                                {
                                    goto StartPnx;
                                }
                            }
                            else
                            {
                                goto Start;
                            }
                        }
                    }

                    goto Start;
                }
                catch (System.Exception ex)
                {
                }
            } while (true);
        }

        public void CallBat(string BatchFilePath)
        {
            try
            {
                //设置要执行的批处理文件路径和名称
                string batchFile = BatchFilePath;

                //创建ProcessStartInfo对象，设置相关属性
                var startInfo = new ProcessStartInfo(batchFile)
                {
                    //设置使用Shell执行批处理
                    UseShellExecute = false,
                    //设置不显示窗口
                    CreateNoWindow = true,
                    //设置标准输出、错误输出异步读取
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                //启动进程
                var process = Process.Start(startInfo);

                //等待进程执行结束
                process.WaitForExit();
            }
            catch (System.Exception ex)
            {

            }
        }
    }
}